package org.jeecg.hr.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.jeecg.hr.entity.AssessmentRule;
import org.jeecg.hr.entity.AssessmentTaskResultSummary;
import org.jeecg.hr.mapper.AssessmentRuleMapper;
import org.jeecg.hr.mapper.AssessmentTaskResultSummaryMapper;
import org.jeecg.hr.service.AssessmentRuleService;
import org.jeecg.hr.vo.AssessmentResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
public class AssessmentRuleServiceImpl extends ServiceImpl<AssessmentRuleMapper, AssessmentRule> implements AssessmentRuleService {

	@Autowired
	private AssessmentRuleMapper assessmentRuleMapper;
	
	@Autowired
	private AssessmentTaskResultSummaryMapper assessmentTaskResultSummaryMapper;
	
	@Override
	public List<AssessmentRule> selectByPlanCode(String planCode) {
		return assessmentRuleMapper.selectByPlanCode(planCode);
	}

	@Override
	public void saveResult(String planCode, String instanceCode) {
		List<AssessmentResultVo> list = assessmentRuleMapper.selectResult(planCode, instanceCode);
		Map<String,AssessmentResultVo> map = list.stream().collect(Collectors.toMap(AssessmentResultVo :: getUsername, Function.identity(),(key1,key2)->key2));
		List<AssessmentTaskResultSummary> summaryList = assessmentTaskResultSummaryMapper.selectList(new QueryWrapper<AssessmentTaskResultSummary>().eq("instance_code", instanceCode));
		summaryList.forEach(summary -> {
			AssessmentResultVo vo = map.get(summary.getUsername());
			if(vo != null){
				summary.setAssessmentScore(vo.getAssessmentScore()== null ? BigDecimal.ZERO : vo.getAssessmentScore());
				summary.setLevelDesc(vo.getLevelDesc());
				assessmentTaskResultSummaryMapper.updateById(summary);
			}
		});
	}

}
